<?php

/**
 * 商品分类控制器
 */
class Controller_Category extends Controller_Abstract
{
    function actionIndex()
    {
       
    }

	
    function actionList(){
    
    	//--判断是否是comobotree 调用
    	$flag=$this->_context->get('comobotree',0);
    	if(!$flag){
    		$list = Category::find()->order('category_id')->asArray()->getAll();    	
    		$tree = Helper_Array::toTree($list, 'category_id','parent','children');
    	}
    	else{
    		$columns=new QDB_Expr('category_id as id,CONCAT(name," (" ,code,")") as text,[parent]');
    		$list = Category::find()->setColumns($columns)->order('category_id')->asArray()->getAll();    	
    		$tree = Helper_Array::toTree($list, 'id','parent','children');
    		$a=array("id"=>0,"text"=>"顶级类别",'parent' => 0);
    		array_unshift($tree,$a);
    	}
    	
    	$str = json_encode($tree);
    
    	return $str;
    }
    
    function actionNew(){
    	
    	$category = new Category($_POST);
    	
	    try {
	    	
	    	$category->save();
			return json_encode(array('success'=>true));
			
		} catch (QDB_ActiveRecord_ValidateFailedException $e) {			
			
			return json_encode(array('errorMsg' => $e->getMessage()));			
		}
    }
    function actionUpdate(){
    	$id=$this->_context->post('category_id');
    	$category = Category::find('category_id=?',$id)->getOne();
    	
    	$category->changeProps($_POST);
    	
    	try{
    		$category->save();
    		return  json_encode(array('success'=>true));
    	
    	} catch (QDB_ActiveRecord_ValidateFailedException $e) {			
			
			return json_encode(array('errorMsg' => $e->getMessage()));			
		}
    }
    
    function actionDestroy(){
    	
    	$id=$this->_context->post('id',0);
    	$row=Category::find("category_id=?",$id)->getOne();

    	try {
    		if(count($row->children) > 0){
    			return json_encode(array('errorMsg'=>'该类别下面包含子类别，不能删除，请先删除子类别.'));
    		}
    		else{
    			$row->destroy();
				return  json_encode(array('success'=>true));
    		}
    	}
    	catch (Exception $e){
				return json_encode(array('errorMsg'=>'系统出错,操作未能完成.'));
		}
    }
}

